package com.gis.visualization.utils.timeutils;

import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TimeFormat {
    /**
     * 45      * 将长整型数字转换为日期格式的字符串
     * 46      * @param time
     * 47      * @param format
     * 48      * @return
     * 49
     */
    public static Date timeStrDeal(String time) throws ParseException {

        if (!StringUtils.isEmpty(time)) {
            if(appearNumber(time,"-") == 0) {
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy");
                return sdf.parse(time);
            }else if (appearNumber(time,"-") == 1){
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM");
                return sdf.parse(time);
            }else if (appearNumber(time,"-") == 2){
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                return sdf.parse(time);
            }
        }
        return new Date();
    }

    /**
     * 获取指定字符串出现的次数
     *
     * @param srcText 源字符串
     * @param findText 要查找的字符串
     * @return
     */
    public static int appearNumber(String srcText, String findText) {
        int count = 0;
        Pattern p = Pattern.compile(findText);
        Matcher m = p.matcher(srcText);
        while (m.find()) {
            count++;
        }
        return count;
    }

    public static void main(String[] args) {
//        String s = timeStrDeal("2021-02");

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy");//小写的mm表示的是分钟
        String dstr="2000";
        try {
            Date date=sdf.parse(dstr);
            System.out.println(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
